package cn.itsource.ymcc.web.controller;

import cn.itsource.ymcc.context.LoginContext;
import cn.itsource.ymcc.domain.CourseUserLearn;
import cn.itsource.ymcc.dto.CourseAddDto;
import cn.itsource.ymcc.dto.CourseDetailDto;
import cn.itsource.ymcc.dto.CourseInfoDto;
import cn.itsource.ymcc.service.ICourseService;
import cn.itsource.ymcc.domain.Course;
import cn.itsource.ymcc.query.CourseQuery;
import cn.itsource.ymcc.result.JSONResult;
import cn.itsource.ymcc.result.PageList;
import cn.itsource.ymcc.service.ICourseUserLearnService;
import cn.itsource.ymcc.vo.CourseInfoForOrder;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    public ICourseService courseService;

    @Autowired
    private ICourseUserLearnService courseUserLearnService;


    /**
     * 课程发布
     */
    @PreAuthorize("hasAuthority('course:online')")
    @RequestMapping(value="/onLineCourse/{id}",method= RequestMethod.POST)
    public JSONResult onLineCourse(@PathVariable("id")Long id){
        courseService.onLineCourse(id);
        return JSONResult.success();
    }

    /**
     * 查看用户的课程
     */
    @RequestMapping(value = "/listForUser",method = RequestMethod.GET)
    public JSONResult listForUser(){
        Long userId = LoginContext.getLogin().getId();
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("login_id",userId);
        List<CourseUserLearn> courseUserLearns = courseUserLearnService.selectList(wrapper);
        //查询课程
        List<Course> courses = courseService.selectBatchIds(courseUserLearns.stream().map(c -> c.getCourseId()).collect(Collectors.toList()));
        return JSONResult.success(courses);
    }


    /**
     * 获取课程详情
     */
    @RequestMapping(value = "/info/json/{id}",method = RequestMethod.GET)
    public JSONResult getCourseInfoForJSON(@PathVariable("id")Long id){
        return JSONResult.success(JSON.toJSONString(courseService.selectCourseInfoById(id)));
    }


    /**
     * 获取课程详情
     */
    @RequestMapping(value = "/infos/json",method = RequestMethod.POST)
    public JSONResult getCourseInfosForJSON(@RequestBody List<Long> courseIds){
        return JSONResult.success(JSON.toJSONString(courseService.selectCourseInfosById(courseIds)));
    }


    /**
     * 获取对象
     */
    @RequestMapping(value = "/info/{ids}",method = RequestMethod.GET)
    public JSONResult getCourseInfo(@PathVariable("ids")String ids){
        List<Long> longIds = Arrays.asList(ids.split(",")).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());
        List<CourseInfoDto> courseInfoDtos = courseService.selectCourseInfosById(longIds);
        //计算总额
        AtomicReference<BigDecimal> total = new AtomicReference<>(new BigDecimal("0.00"));
        courseInfoDtos.stream().forEach(info-> {
            total.set(info.getCourseMarket().getPrice().add(total.get()));
        });
        return JSONResult.success(new CourseInfoForOrder(courseInfoDtos,total.get()));
    }


    /**
     * 加载课程数据
     */
    @RequestMapping(value="/detail/data/{id}",method= RequestMethod.GET)
    //@PreAuthorize("isAnonymous()")
    public JSONResult selectDetailData(@PathVariable("id") Long id){
        CourseDetailDto courseDetailDto = courseService.selectDetailData(id);
        return JSONResult.success(courseDetailDto);
    }


    /**
     * 保存
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public JSONResult save(@RequestBody CourseAddDto dto){
        courseService.save(dto);
        return JSONResult.success();
    }



    /**
    * 删除对象
    */
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public JSONResult delete(@PathVariable("id") Long id){
        courseService.deleteById(id);
        return JSONResult.success();
    }

    /**
     * 获取对象
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public JSONResult get(@PathVariable("id")Long id){
        return JSONResult.success(courseService.selectById(id));
    }

    /**
    * 查看所有
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public JSONResult list(){
        return JSONResult.success(courseService.selectList(null));
    }


    /**
    * 分页查询数据
    */
    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)
    public JSONResult json(@RequestBody CourseQuery query){
        Page<Course> page = new Page<Course>(query.getPage(),query.getRows());

        Wrapper<Course> wrapper = new EntityWrapper<>();

        if(StringUtils.hasLength(query.getKeyword())){
            wrapper.like("name",query.getKeyword());
        }
        page = courseService.selectPage(page,wrapper);
        return JSONResult.success(new PageList<Course>(page.getTotal(),page.getRecords()));
    }
}
